package net.togogo.mp.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.annotation.Resource;
import net.togogo.mp.domain.User;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;

import net.togogo.mp.domain.dto.UserFormDTO;
import net.togogo.mp.domain.dto.UserQuery;
import net.togogo.mp.domain.vo.UserVO;
import net.togogo.mp.mapper.UserMapper;
import net.togogo.mp.service.IUserService;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.executor.BatchResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *
 * </p>
 *
 * @author YYD
 * @since 2025/9/19
 */
@Tag(name = "用户接口", description = "用户相关操作接口")
//1.让UserController封装为bean
//2.所有的响应都返回json格式的数据
@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
  private UserMapper userMapper;
    @Autowired
    private IUserService userService;
    @PostMapping
    @Operation(summary = "添加用户")
    public void saveUser(@RequestBody UserFormDTO userFormDTO){
        userMapper.save(userFormDTO);
    }
    @DeleteMapping("/{id}")
    @Operation(summary = "删除用户")
    public void deleteUser(@PathVariable Long id){
        userMapper.deleteById(id);
    }
    @GetMapping("/{id}")
    @Operation(summary = "查询用户")
    public UserVO getUser(@PathVariable Long id){
        return userMapper.getById(id);
    }
    @GetMapping
    @Operation(summary = "查询所有用户")
    public List<UserVO> listUsers(){
        return userMapper.list();
    }

    @GetMapping("/list")
    @Operation(summary = "根据自定义条件查询用户")
    public List<UserVO> queryUsers(UserQuery query){
        // 1.组织条件
        String username = query.getName();
        Integer status = query.getStatus();
        Integer minBalance = query.getMinBalance();
        Integer maxBalance = query.getMaxBalance();
        LambdaQueryWrapper<User> wrapper = new QueryWrapper<User>().lambda()
                .like(username != null, User::getUsername, username)
                .eq(status != null, User::getStatus, status)
                .ge(minBalance != null, User::getBalance, minBalance)
                .le(maxBalance != null, User::getBalance, maxBalance);
        // 2.查询用户
        List<User> users = userService.list(wrapper);
        // 3.处理vo
        return users.stream().map(user -> {
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user, userVO);
            return userVO;
        }).collect(Collectors.toList());
    }

}
